package com.zoe.app.filter;


import com.zoe.app.config.RepeatedlyRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zoe.Zhang
 * @date 2022/06/09
 * @description
 */
@Slf4j
public class GlobalFilter extends OncePerRequestFilter {


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        ServletRequest requestWrapper = null;
        log.info("进入过滤器====>");

        // 只针对APPLICATION_JSON_VALUE的数据请求才会包装一下request
        if (StringUtils.startsWithIgnoreCase(request.getContentType(), MediaType.APPLICATION_JSON_VALUE)) {
            requestWrapper = new RepeatedlyRequestWrapper(request);
        }
        if (null == requestWrapper) {
            filterChain.doFilter(request, response);
        }
        else {
            filterChain.doFilter(requestWrapper, response);
        }

        // 如果不使用包装后的过滤器 就会导致读取一次就无法读取了
        // filterChain.doFilter(request, response);
        log.info("离开过滤器====>");
    }
}
